//
//  LoginController.m
//  HarmonizePub
//
//  Created by rzhy on 16/8/20.
//  Copyright © 2016年 Zy. All rights reserved.
//

#import "LoginController.h"
#import <YYModel.h>
#import "Config.h"
#import "Utils.h"
#import "UIBarButtonItem+Zy.h"
#import "User.h"
#import "UserSignController.h"
#import "ForgotPwdController.h"
#import "JPUSHService.h"

@interface LoginController () <UITextFieldDelegate, UserSignControllerDelegate, ForgotPwdControllerDelegate>

@property (weak, nonatomic) IBOutlet UITextField *userNameField;
@property (weak, nonatomic) IBOutlet UITextField *passWordField;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;

@end

@implementation LoginController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.loginButton.layer.cornerRadius = 5.0f;
    self.loginButton.layer.masksToBounds = YES;
    
    NSString *userName = [UserDefaultsTool stringForKey:XHUserName];
    if (userName) {
        self.userNameField.text = userName;
        [self.passWordField becomeFirstResponder];
    } else
        [self.userNameField becomeFirstResponder];
}

- (IBAction)back:(UIButton *)sender {
    [self.view endEditing:NO];
    [self dismissViewControllerAnimated:YES completion:nil];
    if ([_delegate respondsToSelector:@selector(cancelLogin:)])
        [self.delegate cancelLogin:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 登录
- (IBAction)loginEvent:(UIButton *)sender {
    NSString *userName = self.userNameField.text;
    NSString *passWord = self.passWordField.text;
    if (!userName || [userName isEqualToString:@""]) {
        [self setAlertViewWithMessage:@"请输入手机号码!"];
    } else if (![Utils matchingTelNumber:userName]) {
        [self setAlertViewWithMessage:@"请输入正确的手机号码!"];
    } else if (!passWord || [passWord isEqualToString:@""]) {
        [self setAlertViewWithMessage:@"请输入密码!"];
    } else if (passWord.length <= 0 || passWord.length > 16) {
        [self setAlertViewWithMessage:@"请输入正确的密码!\n密码由1-16位数字和字母组成!"];
    } else {
        [self.view endEditing:NO];
        NSDictionary *param = @{@"userName" : userName, @"password" : passWord, @"type" : @(1)};
        __unsafe_unretained LoginController *weakSelf = self;
        [HTTPSTool GETRequestWithPath:XHLoginPath params:param success:^(NSDictionary * _Nonnull JSON) {
//            XHLog(@"登录 -> JSON: %@", JSON)
            [weakSelf dataOperationWithDataDictionary:JSON[@"data"]];
        }];
    }
}

- (void)dataOperationWithDataDictionary:(NSDictionary *)dataDict {
    NSString *token = [@"token=" stringByAppendingString:dataDict[@"token"]];
    [UserDefaultsTool setObject:token forKey:XHToken];
    
    NSDictionary *userDict = dataDict[@"user"];
    User *user = [User yy_modelWithDictionary:userDict];
    [UserDefaultsTool setObject:user.userName forKey:XHUserName];
    [NSKeyedArchiver archiveRootObject:user toFile:XHUserPath];
    
    [UserDefaultsTool setObject:dataDict[@"count"] forKey:XHNewMessage];
    [[NSNotificationCenter defaultCenter] postNotificationName:XHNewMessage object:nil userInfo:nil];
    
    [JPUSHService setTags:nil alias:user.token fetchCompletionHandle:^(int iResCode, NSSet *iTags, NSString *iAlias) {
        XHLog(@"登录注册别名 -> iResCode: %d, iTags: %@, iAlias: %@", iResCode, iTags, iAlias);
    }];
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
    if ([_delegate respondsToSelector:@selector(loginSuccessCallback:)])
        [_delegate loginSuccessCallback:self];
    
    [self storagePatientListDataWithDataArray:dataDict[@"brdaList"]];
}

#pragma mark - 注册
- (IBAction)signEvent:(UIButton *)sender {
    UserSignController *userSignController = [[UserSignController alloc] init];
    userSignController.delegate = self;
    [self presentViewController:userSignController animated:YES completion:nil];
}

- (void)signSuccessWithUserName:(NSString *)name passWord:(NSString *)passWord {
    self.userNameField.text = name;
    self.passWordField.text = passWord;
    [self loginEvent:self.loginButton];
}

#pragma mark - 忘记密码
- (IBAction)forgotPassWordEvent:(UIButton *)sender {
    ForgotPwdController *forgot = [[ForgotPwdController alloc] init];
    forgot.delegate = self;
    [self presentViewController:forgot animated:YES completion:nil];
    forgot.phoneNum = self.userNameField.text;
}

- (void)forgotPwdController:(ForgotPwdController *)ForgotPwdController phone:(NSString *)phone passWord:(NSString *)passWord {
    self.userNameField.text = phone;
    self.passWordField.text = passWord;
}

#pragma mark - 显示/隐藏密码
- (IBAction)switchShowAndHidenPassWordEvent:(UIButton *)sender {
    sender.selected = !sender.selected;
    self.passWordField.secureTextEntry = !sender.selected;
}

#pragma mark - 储存就诊列表数据
- (void)storagePatientListDataWithDataArray:(NSArray *)dataArray {
    NSMutableArray *medicalArray = [NSMutableArray array];
    NSMutableArray *inpatientArray = [NSMutableArray array];
    for (NSDictionary *dataDict in dataArray) {
        if ([dataDict[@"bindType"] integerValue] == 1)
            [medicalArray addObject:dataDict];
        else
            [inpatientArray addObject:dataDict];
    }
    NSMutableDictionary *rootDict = [NSMutableDictionary dictionary];
    if (medicalArray.count) [rootDict setValue:medicalArray forKey:XHMedicalListKey];
    if (inpatientArray.count) [rootDict setValue:inpatientArray forKey:XHInpatientLisyKey];
    [rootDict writeToFile:XHPatientListPath atomically:YES];
}

#pragma mark - textField delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - AlertView
- (void)setAlertViewWithMessage:(NSString *)message {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示:" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:defaultAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:NO];
}

@end
